package com.bjtu.boatmq.common;

import com.bjtu.boatmq.common.protocol.PacketSource;
import com.bjtu.boatmq.common.protocol.SourceDecoder;
import com.bjtu.boatmq.common.protocol.SourceEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import javax.xml.transform.Source;
import java.util.Date;
//import com.bjtu.boatmq.common.NettyServer;

public class NettyClient {

    private String address;
    private int port;
    private PacketSource packetSource;
    
//    public NettyClient(String address,int port,PacketSource packetSource){
//        this.address = address;
//        this.port = port;
//        this.packetSource = packetSource;
//    }
    public NettyClient(String address,int port) {
    	this.address = address;
    	this.port = port;
    }
    
    public  void send(PacketSource packetSource) throws InterruptedException{
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new SourceEncoder());
                        ch.pipeline().addLast(new SourceDecoder());
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });
        
        Channel channel = bootstrap.connect(address, port).channel();
//        PacketSource ps = new PacketSource();
        while (true){
            channel.writeAndFlush(packetSource);
            Thread.sleep(1000);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        PacketSource ps = new PacketSource();
        NettyClient nc = new NettyClient("127.0.0.1",8000);
        nc.send(ps);
    }
}




